<template>
  <div class="mine-container">
    <jblForm :ref-name.sync="formRef" :form.sync="form" :value-data="form.valueData">
      <template v-slot:form-title1>
        <div class="title">
          <span>1.</span>
          个人基本信息
        </div>
      </template>
      <template v-slot:form-title2>
        <div class="title">
          <span>2.</span>
          学历资料
        </div>
      </template>
      <template v-slot:form-title3>
        <div class="title">
          <span>3.</span>
          账号设置
        </div>
      </template>
      <template v-slot:form-avatar>
        <el-upload
          class="avatar-uploader"
          action="#"
          accept=".jpg, .jpeg, .png, .JPG, .JPEG"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="handleAvatar"
        >
          <img v-if="form.valueData.avatar" :src="form.valueData.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </template>
      <template v-slot:form-phone>
        <el-input
          style="width:150px"
          placeholder="手机号码"
          v-model="form.valueData.phone"
          :disabled="true"
        ></el-input>
        <span class="text" style="margin-left:10px" @click="phoneDialog=true">更改</span>
      </template>
      <template v-slot:form-three>
        <span v-if="userWxBind" class="text" style="margin-left:10px" @click="wxOutBind">解绑</span>
        <span v-else class="text" @click="wxBind">微信绑定</span>
      </template>
      <template v-slot:form-password>
        <span class="text" @click="passwordDialog=true">更改密码</span>
      </template>
    </jblForm>
    <el-row type="flex" justify="center">
      <el-button style="margin-top:30px;width:150px" type="primary" @click="submit">保存</el-button>
    </el-row>
    <!-- 图片裁剪 -->
    <el-dialog
      title="裁剪图片"
      :visible.sync="cropper.dialog"
      width="60%"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="cropperClose"
    >
      <div style="width:400px;height:400px;text-align:center;">
        <VueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.size"
          :outputType="option.outputType"
          :info="true"
          :full="option.full"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :autoCrop="option.autoCrop"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
          :centerBox="option.centerBox"
          :infoTrue="option.infoTrue"
          :fixedBox="option.fixedBox"
        ></VueCropper>
      </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cropper.dialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmCropper">确定裁剪</el-button>
        </div>
    </el-dialog>
    <!-- 更换手机号码 -->
    <el-dialog
      title="更换登录手机号码"
      :visible.sync="phoneDialog"
      width="500px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="phoneRef.resetFields()"
    >
      <jblForm :ref-name.sync="phoneRef" :form.sync="phoneForm" :value-data="phoneForm.valueData">
        <template v-slot:form-code>
          <el-row type="flex">
              <el-input style="width:180px;margin-right:10px" v-model="phoneForm.valueData.code" placeholder="请填写您的验证码"></el-input>
              <el-button v-if="timer===60" type="primary" @click="handleCode">发 送</el-button>
              <el-button v-else type="primary" :disabled="true">已发送({{timer}})</el-button>
          </el-row>
        </template>
      </jblForm>
      <span slot="footer" class="dialog-footer">
        <el-button @click="phoneDialog = false">取 消</el-button>
        <el-button type="primary" @click="changePhone">更 改</el-button>
      </span>
    </el-dialog>
    <!-- 微信绑定 -->
     <el-dialog
      title="微信绑定"
      :visible.sync="wxBindDialog"
      width="700px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
    <div style="width:100%;text-align:center">
       <iframe
        ref="iframeRef"
        class="code-iframe"
        scrolling="no"
        sandbox="allow-scripts allow-top-navigation"
        :src="wxCode">
        </iframe>
    </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="wxBindDialog=false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 更改密码 -->
    <el-dialog
      title="更改密码"
      :visible.sync="passwordDialog"
      width="500px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      @close="passwordRef.resetFields()"
    >
      <jblForm
        :ref-name.sync="passwordRef"
        :form.sync="passwordForm"
        :value-data="passwordForm.valueData"
      ></jblForm>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialog = false">取 消</el-button>
        <el-button type="primary" @click="changePassword">更 改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import md5 from 'js-md5'
import jblForm from '@/components/JblForm'
import { VueCropper } from 'vue-cropper'
import { veryCode } from '@/api/common'
import { getById, updateById } from '@/api/mine'
import { wxUnBind, sendCode, changePhone, setPasswordByOldPwd, getRedirectUrl } from '@/api/user'
export default {
  name: 'MineForm',
  components: {
    jblForm,
    VueCropper
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else {
        if (this.passwordForm.valueData.checkPass !== '') {
          this.passwordRef.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.valueData.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 裁剪组件的基础配置option
      option: {
        mode: 'cover', // 图片默认渲染方式
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 400, // 默认生成截图框宽度
        autoCropHeight: 400, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [400, 400], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      cropper: {
        dialog: false,
        src:
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg',
        width: 400,
        height: 400,
        aspectRatio: 1,
        fileBlob: {}
      },
      phoneDialog: false,
      wxBindDialog: false,
      wxCode: '',
      userWxBind: false, // 是否绑定微信
      formRef: {},
      form: {
        labelWidth: '120px',
        data: [
          {
            type: 'slot',
            prop: 'title1',
            labelWidth: '0',
            show: () => {}
          },
          {
            type: 'slot',
            prop: 'avatar',
            show: () => {},
            label: '头像',
            rules: [
              { required: true, message: '请上传头像', trigger: 'blur' }
            ]
          },
          {
            type: 'input',
            prop: 'realName',
            label: '姓名',
            placeholder: '请填写您的姓名',
            rules: [
              { required: true, message: '请填写您的姓名', trigger: 'blur' },
              {
                min: 1,
                max: 10,
                message: '长度在 1 到 10 个字符',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'radioGroup',
            prop: 'sex',
            show: () => {},
            label: '性别',
            radioGroup: () => {
              return [
                {
                  label: '男',
                  value: 1
                },
                {
                  label: '女',
                  value: 2
                }
              ]
            },
            rules: [
              { required: true, message: '请选择您的性别', trigger: 'blur' }
            ]
          },
          {
            type: 'inputTextarea',
            prop: 'remark',
            label: '简介',
            rows: 4,
            maxlength: 200,
            placeholder: '200字以内',
            rules: [
              { required: true, message: '200字以内', trigger: 'change' },
              {
                min: 1,
                max: 200,
                message: '长度在 1 到 200 个字符',
                trigger: 'blur'
              }
            ]
          },
          {
            type: 'slot',
            prop: 'title2',
            labelWidth: '0',
            show: () => {}
          },
          {
            type: 'input',
            prop: 'graduationSchool',
            label: '毕业院校',
            placeholder: '请填写您的毕业院校',
            rules: [
              {
                required: true,
                message: '请填写您的毕业院校',
                trigger: 'change'
              },
              {
                min: 1,
                max: 40,
                message: '长度在 1 到 20 个字符',
                trigger: 'blur'
              }
            ]
          },
          {
            type: 'select',
            prop: 'education',
            show: () => {},
            label: '学历',
            selectOption: () => {
              return [
                {
                  label: '小学',
                  value: 1
                },
                {
                  label: '初中',
                  value: 2
                },
                {
                  label: '高中',
                  value: 3
                },
                {
                  label: '专科',
                  value: 4
                },
                {
                  label: '本科',
                  value: 5
                },
                {
                  label: '硕士',
                  value: 6
                },
                {
                  label: '博士',
                  value: 7
                }
              ]
            },
            rules: [
              { required: true, message: '请选择您的学历', trigger: 'blur' }
            ]
          },
          {
            type: 'slot',
            prop: 'title3',
            labelWidth: '0'
          },
          {
            type: 'slot',
            prop: 'phone',
            label: '登录账号'
          },
          // {
          //   type: 'slot',
          //   prop: 'three',
          //   show: () => {},
          //   label: '第三方'
          // },
          {
            type: 'slot',
            prop: 'password',
            show: () => {},
            label: '密码设置'
          }
        ],
        valueData: {
          avatar: '',
          phone: ''
        }
      },
      phoneRef: {},
      timer: 60,
      phoneForm: {
        data: [
          {
            type: 'inputNumber',
            prop: 'phone',
            label: '新的手机号',
            labelWidth: '100px',
            placeholder: '请填写您的新手机号',
            rules: [
              { validator: validatePhone, required: true, trigger: 'blur' },
              {
                type: 'number',
                message: '手机号码必须为数字',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'slot',
            prop: 'code',
            show: () => {},
            label: '验证码',
            labelWidth: '100px',
            rules: [
              { required: true, message: '请填写您的验证码', trigger: 'blur' }
            ]
          }
        ],
        valueData: {
          code: ''
        }
      },
      passwordDialog: false,
      passwordRef: {},
      passwordForm: {
        data: [
          {
            type: 'input',
            prop: 'oldPassword',
            label: '原密码',
            placeholder: '请填写您的原密码',
            rules: [
              {
                required: true,
                message: '请填写您的原密码',
                trigger: 'change'
              },
              {
                min: 1,
                max: 20,
                message: '长度在 1 到 20 个字符',
                trigger: 'blur'
              }
            ]
          },
          {
            type: 'input',
            prop: 'password',
            label: '新密码',
            placeholder: '请填写您的新密码',
            rules: [{ required: true, validator: validatePass, trigger: 'blur' }]
          },
          {
            type: 'input',
            prop: 'checkPass',
            label: '确认密码',
            placeholder: '再次输入新密码',
            rules: [{ required: true, validator: validatePass2, trigger: 'blur' }]
          }
        ],
        valueData: {
          passord: '',
          checkPass: ''
        }
      }
    }
  },
  computed: {
  },
  created() {
    getById({
      userId: JSON.parse(localStorage.getItem('userInfo')).id,
      orgId: this.$store.getters.businessId
    }).then(res => {
      this.form.valueData = res.data
      this.formRef.clearValidate()
    })
  },
  mounted() {
    // this.formRef.clearValidate()
  },
  watch: {
    $route(to, from) {
      console.log(from.path)// 从哪来
      console.log(to.path)// 到哪去
    }
  },
  methods: {
    handleAvatar(res, fileList) {
      this.cropper.dialog = true
      this.option.img = URL.createObjectURL(res.file)
    },

    // 确定裁剪
    confirmCropper() {
      this.$refs.cropper.getCropBlob((data) => {
        const raw = {
          raw: data,
          name: new Date().valueOf()
        }
        this.uploadImgToOss(raw)
          .then(response => {
            const { imgUrl } = response
            this.form.valueData.avatar = imgUrl
          })
          .finally(() => {
            this.cropper.dialog = false
          })
      })
    },
    cropperClose() {
      // this.cropper.src = ''
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleCode() {
      this.phoneRef.validateField('phone', err => {
        if (err) {
          return false
        } else {
          this.timer = 59
          const time = setInterval(() => {
            this.timer--
            if (this.timer <= 0) {
              clearInterval(time)
              this.timer = 60
            }
          }, 1000)
          sendCode({ phone: this.phoneForm.valueData.phone }).then(res => {
            this.$message.success('验证码发送成功')
          })
        }
      })
    },
    // 更好手机号码
    changePhone() {
      this.phoneRef.validate(valid => {
        if (valid) {
          veryCode({
            'phone': this.phoneForm.valueData.phone,
            'code': this.phoneForm.valueData.code
          }).then(() => {
            changePhone({
              'id': this.form.valueData.userId,
              'phone': this.phoneForm.valueData.phone,
              'code': this.phoneForm.valueData.code
            }).then(res => {
              this.phoneDialog = false
              this.$message.success('更换成功,请重新登录')
              this.$store.dispatch('user/logout')
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            })
          })
        } else {
          return false
        }
      })
    },
    wxBind() {
      this.wxBindDialog = true
      if (this.wxCode) return
      getRedirectUrl().then(res => {
        this.wxCode = `${res.data}&self_redirect=false`
      })
    },
    wxOutBind() {
      wxUnBind({
        'unionId': '1',
        'openId': '94528',
        'bindType': 'VrtltharcK',
        'thirdAppId': '94886'
      }).then(res => {
        this.$message.success('解绑成功')
      })
    },
    // 更改密码
    changePassword() {
      this.passwordRef.validate(valid => {
        if (valid) {
          setPasswordByOldPwd(
            {
              'id': this.form.valueData.userId,
              'phone': this.form.valueData.phone,
              'oldPassword': md5(this.passwordForm.valueData.oldPassword),
              'password': md5(this.passwordForm.valueData.password)
            }
          ).then(res => {
            this.$message({
              message: '更改成功',
              type: 'success'
            })
            this.passwordDialog = false
          })
        } else {
          return false
        }
      })
    },
    submit() {
      this.formRef.validate((valid,obj) => {
        if (valid) {
          updateById(
            {
              // id: this.form.valueData.userId,
              // info: {
              realName: this.form.valueData.realName,
              id: this.form.valueData.id,
              avatar: this.form.valueData.avatar,
              sex: this.form.valueData.sex,
              remark: this.form.valueData.remark,
              graduationSchool: this.form.valueData.graduationSchool,
              education: this.form.valueData.education
            }
            // }
          ).then(res => {
            this.$message.success('保存成功')
          })
        } else {
          this.$message.error('请完善页面信息')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.mine-container{
  padding: 20px 50px;
}
.title {
  margin-top: 20px;
  font-size: 24px;
  font-weight: 600;
  > span {
    color: rgb(5, 226, 226);
  }
}
/deep/.el-input{
  width: 300px;
}
/deep/.el-textarea{
  width: 50%;
}
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
/deep/.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
/deep/.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.text {
  cursor: pointer;
  color: red;
}
.code-iframe {
    width: 300px;
    height: 400px;
    border: none;
    overflow-y: hidden;
    /deep/.impowerBox .title{
      display: none;
    }
  }
</style>
